import os
import imageio
import shutil



def convert_gif_to_mp4(input_folder, output_folder):

    # 检查输出文件夹是否存在，不存在则创建
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 遍历输入文件夹中的文件
    for file_name in os.listdir(input_folder):
        # 筛选出后缀为 .webp 的文件
        if file_name.endswith('.webp'):
            file_path = os.path.join(input_folder, file_name)
            # 构造输出文件路径，把 .webp 替换成 .mp4
            output_file_path = os.path.join(output_folder, file_name[:-4] + '.mp4')

            frames = []
            # 读取 webp 动图的每一帧
            with imageio.get_reader(file_path, 'webp') as reader:
                for frame in reader:
                    frames.append(frame)

            # 将帧序列写入为 MP4 视频，设置帧率为 10
            with imageio.get_writer(output_file_path, mode='I', fps=10) as writer:
                for frame in frames:
                    writer.append_data(frame)
            print(f"{file_name} 已成功转换为 {output_file_path}")


def list_folders(dir_path):
        """返回指定目录下的所有文件夹名称（使用 os.scandir）"""
        folders = []
        with os.scandir(dir_path) as entries:
            for entry in entries:
                if entry.is_dir():
                    folders.append(entry.name)
        return folders

if __name__ == "__main__":

    basePath = "C:\\Users\\haoxi\\Desktop\\test2"
    folders  = list_folders(basePath)

    for folder_name in folders:
        print(folder_name)  # 输出文件夹名称

        # 替换为实际存放 webp 文件的文件夹路径
        input_folder_path = basePath + "\\"+folder_name +"\\temp"
        if not os.path.exists(input_folder_path):
            print(f"目录 {input_folder_path} 不存在！")
            continue

        # 替换为实际要保存 MP4 文件的文件夹路径
        output_folder_path = basePath + "\\"+folder_name
        convert_gif_to_mp4(input_folder_path, output_folder_path)
        shutil.rmtree(input_folder_path)  # 递归删除所有文件和子文件夹






